import fs from 'fs'
import path from 'path'
import { DATA_DIR } from '../config/env.js'

// ensure data dir
if (!fs.existsSync(DATA_DIR)) {
  fs.mkdirSync(DATA_DIR, { recursive: true })
}

export function getDataPath(userId) {
  return path.join(DATA_DIR, `${userId}.json`)
}

export function loadUserData(userId) {
  const filePath = getDataPath(userId)
  try {
    if (fs.existsSync(filePath)) {
      return JSON.parse(fs.readFileSync(filePath, 'utf8'))
    }
  } catch (e) {
    console.error('读取用户数据失败:', e)
  }
  return {
    userId,
    subjects: {},
    practiceRecords: [],
    settings: { theme: 'light', difficulty: 'medium', notifications: true },
    createdAt: new Date().toISOString(),
  }
}

export function saveUserData(userId, data) {
  const filePath = getDataPath(userId)
  try {
    fs.writeFileSync(filePath, JSON.stringify(data, null, 2))
    return true
  } catch (e) {
    console.error('保存用户数据失败:', e)
    return false
  }
}

const USERS_FILE = path.join(DATA_DIR, 'users.json')

export function loadUsers() {
  try {
    if (fs.existsSync(USERS_FILE)) {
      return JSON.parse(fs.readFileSync(USERS_FILE, 'utf8'))
    }
  } catch (e) {
    console.error('读取用户列表失败:', e)
  }
  return { users: [] }
}

export function saveUsers(data) {
  try {
    fs.writeFileSync(USERS_FILE, JSON.stringify(data, null, 2))
    return true
  } catch (e) {
    console.error('保存用户列表失败:', e)
    return false
  }
}
